﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Microsoft.Extensions.Configuration
{
    public static class ConfigurationExtension
    {
        public static string GetValueFromManyChanels(this IConfiguration configuration, string key)
        {
            return GetEnvironmentVariable(configuration[key], configuration);
        }

        private static string GetEnvironmentVariable(string value, IConfiguration configuration)
        {
            if (string.IsNullOrEmpty(value)) return value;
            var result = value;
            var param = GetParameters(result).FirstOrDefault();
            if (!string.IsNullOrEmpty(param))
            {
                //优先从控制台传参取值
                var console = configuration[param];
                if (!string.IsNullOrEmpty(console))
                {
                    return GetRealValue(console, console);
                }
                //其次充环境变量取值
                var env = Environment.GetEnvironmentVariable(param);
                result = env;
                if (string.IsNullOrEmpty(env))
                {
                    //最后从配置文件取值
                    result = GetRealValue(value, env);
                }
            }
            return result;
        }

        private static string GetRealValue(string value, string env)
        {
            var index = value.IndexOf("|");
            if (index >= 0)
            {
                return value.Substring(index+1);
            }
            return env;
        }

        private static List<string> GetParameters(string text)
        {
            var matchVale = new List<string>();
            string Reg = @"(?<=\${)[^\${}]*(?=})";
            string key = string.Empty;
            foreach (Match m in Regex.Matches(text, Reg))
            {
                matchVale.Add(m.Value);
            }
            return matchVale;
        }
    }
}
